{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在Pandas库中，.loc 是用来基于标签（即行索引和列标签）进行选择和修改的定位器（locator）。\n",
    "而 .loc 是该对象的一个属性，它允许你通过行标签和列标签来选择或设置数据。\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd  \n",
    "  \n",
    "# 创建一个简单的DataFrame  \n",
    "data = {  \n",
    "    'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve'],  \n",
    "    'Math': [85, 92, 78, 90, 88],  \n",
    "    'English': [90, 88, 92, 85, 91]  \n",
    "}  \n",
    "df = pd.DataFrame(data)  \n",
    "  \n",
    "print(\"原始DataFrame:\")  \n",
    "print(df)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "到所有数学分数超过90的学生，并将他们的英语分数增加5分。我们可以使用 df.loc 来实现这个操作：\n",
    "\n",
    "\n",
    "使用 .loc 的基本语法是\n",
    "df.loc[row_indexer, column_indexer]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "修改后的DataFrame:\n",
      "      Name  Math  English\n",
      "0    Alice    85       90\n",
      "1      Bob    92       93\n",
      "2  Charlie    78       92\n",
      "3    David    90       85\n",
      "4      Eve    88       91\n"
     ]
    }
   ],
   "source": [
    "# 选择所有数学分数超过90的学生的索引  \n",
    "high_math_scores = df['Math'] > 90  # 创建了一个布尔Series high_math_scores，它标记了哪些学生的数学分数超过90。\n",
    "  \n",
    "# 使用这些索引来选择对应的行，并增加英语分数  \n",
    "# 使用这个布尔Series和 df.loc 来选择这些学生的行，并将他们的英语分数增加5分。\n",
    "df.loc[high_math_scores, 'English'] += 5  \n",
    "  \n",
    "print(\"修改后的DataFrame:\")  \n",
    "print(df)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
